"use client";

import WebrtcNav from '@/components/WebrtcNav';
import { useState, useRef } from 'react';

const Record = () => {
  const [isRecording, setIsRecording] = useState(false);
  const [mediaRecorder, setMediaRecorder] = useState<MediaRecorder | null>(null);
  const streamRef = useRef<MediaStream | null>(null);
  const videoRef = useRef<HTMLVideoElement>(null);
  const bufferRef = useRef<Blob[]>([]);
  const [videoUrl, setVideoUrl] = useState('');

  function handleDataAvailable(e: BlobEvent) {        
    if(e && e.data && e.data.size > 0) {               
      bufferRef.current.push(e.data);
    }
  }

  const startRecord = async () => {
    try {
      // 获取用户媒体流
      const stream = await navigator.mediaDevices.getUserMedia({ 
        video: {
            height:{min: 480,ideal: 720,max: 1080},
            width:{min: 640,ideal: 1280,max: 1920},
        }, 
        audio: true 
      });
      !streamRef.current &&  (streamRef.current = stream);

      const options = { mimeType: 'video/webm;codecs=vp8' };
      
      // 判断浏览器是否支持录制 
      if(!MediaRecorder.isTypeSupported(options.mimeType)) { 
        console.error(`${options.mimeType} is not supported!`); 
        return; 
      }

      // 创建录制对象 
      const recorder = new MediaRecorder(streamRef.current, options);
      recorder.ondataavailable = handleDataAvailable;
      recorder.start();
      
      setMediaRecorder(recorder);
      setIsRecording(true);
    } catch(e) { 
      console.error('Failed to start recording:', e); 
      return;
    }
  };

  const stopRecord = () => {
    if (mediaRecorder && isRecording) {
      mediaRecorder.stop();
      setIsRecording(false);
      
      // 停止所有媒体轨道
      if (streamRef.current) {
        streamRef.current.getTracks().forEach(track => track.stop());
        // mediaRecorder.stream = null;
      }
    }
  };
  const IsPC = () => { 
    return navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i) ? false : true;
  };
  const startDisplay = () => { 
    if(IsPC()){ 
        //开始捕获桌面数据 
        navigator.mediaDevices.getDisplayMedia({video: true}) .then((stream) => {
            streamRef.current = stream;
            videoRef.current &&  (videoRef.current.srcObject = stream);
        }) .catch((err) => {
            console.error('Failed to start display capture:', err);
        }); return true; } return false;
  };

  return (
    <div>
     	<WebrtcNav text={'record'}></WebrtcNav>
      <div className="shadow-md py-2">
        <div className="flex space-x-2 my-2 py-2 border-b border-gray-300">
          {!isRecording ? (
            <button 
                type='button'
              onClick={startRecord}
              className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
            >
              开始录制
            </button>
          ) : (
            <button 
            type='button'
              onClick={stopRecord}
              className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded"
            >
              停止录制
            </button>

          )}
          <button 
          type='button'
          disabled={isRecording}
            onClick={() => {
              if (bufferRef.current.length > 0) {
                const blob = new Blob(bufferRef.current, { type: 'video/webm' });
                const url = URL.createObjectURL(blob);
                videoRef.current && (videoRef.current.srcObject = null);
                setVideoUrl(url);

                // setVideoUrl(url);
                streamRef.current = null;
                // window.open(url);
              }
            }}
            className="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded"
          >播放</button>
          <button 
            onClick={() => {
            //   setVideoUrl('');
            //   bufferRef.current = [];
            // if(videoUrl){
                const blob = new Blob(bufferRef.current, { type: 'video/webm' });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a')
                a.href = url;
                a.download = 'record.webm';
                a.click();
            // }
            }}
            className="bg-gray-500 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded"
          >下载</button>
          <button className='bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded' onClick={startDisplay}>抓取桌面</button>
        </div>
        <div className='my-2 flex justify-center'>
            <video ref={videoRef} src={videoUrl} controls autoPlay width={640} height={360}></video>
        </div>
      </div> 
    </div>
  );
};

export default Record;

function IsPC() {
    throw new Error('Function not implemented.');
}
